package com.example.hasee.zhcd.Activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hasee.zhcd.Base.BaseActivity;
import com.example.hasee.zhcd.Bean.EventMsg;
import com.example.hasee.zhcd.R;
import com.example.hasee.zhcd.Util.GlobalParameter;
import com.example.hasee.zhcd.Util.ProgressDialogUtils;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by hasee on 2018/5/9.
 */

public class LoginActivity extends BaseActivity {
    private EditText username;
    private EditText password;
    private CheckBox auto_login;
    private Button login;
    private String usernameString;
    private String passwordString;
    private Boolean zddl = false;
    private String token;
    private String strIMEI;

    @Override
    public int contentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void set() {
        login.setOnClickListener(this);
        auto_login.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    zddl = true;
                } else {
                    zddl = false;
                }
            }
        });
    }

    @Override
    public void init() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        strIMEI = tm.getDeviceId();
        token = getIntent().getExtras().getString("token");
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        auto_login = (CheckBox) findViewById(R.id.auto_login);
        login = (Button) findViewById(R.id.btn_login);
    }

    @Override
    public void getEventData(EventMsg msg) {
        switch (msg.getAction()) {
            case "ZH_Login":
                ProgressDialogUtils.closeProgressDialog();
//                Log.e("ZHLogin", msg.getMsg());
//                ZHLogin: {"data": {"user":"许洪霞", "role":""},"rspcode": 2,"rspmessage":""}
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.get("rspcode").toString();
                    String rspmessage = json.getString("rspmessage");
                    if ("1".equals(rspcode)) {
                        Toast.makeText(LoginActivity.this, rspmessage, Toast.LENGTH_LONG).show();
                    } else if ("2".equals(rspcode)) {
                        jumpbinddialog(rspmessage);
                    } else if ("3".equals(rspcode)) {
                        JSONObject data = json.getJSONObject("data");
                        HashMap<String, String> loginfomap = new HashMap<String, String>();
                        //{"user":"许洪霞", "role":"", "account":"805", "user":"5530"}
                        loginfomap.put("user", data.getString("user"));
                        loginfomap.put("role", data.getString("role"));
                        loginfomap.put("account", data.getString("account"));
                        loginfomap.put("phone", usernameString);
                        GlobalParameter.put("loginmap", loginfomap);
                        GlobalParameter.putString("rspcode", rspcode);
                        if (zddl) {
                            SharedPreferences sharedPreferences = getSharedPreferences(
                                    "userInfo", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();// 获取编辑器
                            editor.putString("yhm", usernameString.trim());
                            editor.putString("pwd", passwordString.trim());
                            editor.putString("token", token.trim());
                            editor.commit();
                        }
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("token", token);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    } else if ("3".equals(rspcode)) {
                        Toast.makeText(LoginActivity.this, rspmessage, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void getLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strAccount", usernameString);
        map.put("strPassword", passwordString);
        map.put("strTOKEN", token);
        map.put("strIMEI", strIMEI);
        httpUtils.get("ZH_Login", map, "ZH_Login");
    }

    private View inputCheck() {
        if (usernameString.length() == 0) {
            Toast.makeText(LoginActivity.this, "请输入用户名!", Toast.LENGTH_LONG).show();
            return username;
        } else if (passwordString.length() == 0) {
            Toast.makeText(LoginActivity.this, "请输入密码!", Toast.LENGTH_LONG).show();
            return password;
        }
        return null;
    }

    public void initSystemBarTint(boolean on, int res) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(on);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(on);
            tintManager.setStatusBarTintResource(res);
        }
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    private void jumpbinddialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setMessage(message);
        builder.setTitle("提示");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
                Intent intent = new Intent(LoginActivity.this, BindActivity.class);
                intent.putExtra("phone", usernameString);
                startActivity(intent);
            }
        });
        builder.create().show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                usernameString = username.getText().toString().trim();
                passwordString = password.getText().toString().trim();
                View errorview = inputCheck();
                if (errorview != null) {
                    errorview.setFocusable(true);
                    errorview.requestFocus();
                    errorview.setFocusableInTouchMode(true);
                    return;
                } else {
                    ProgressDialogUtils.createProgressDialog(LoginActivity.this, "正在登录...");
                    getLogin();
                }
                break;
        }
    }
}
